//
//  UICustomTextAlertView.m
//  UICustomTextAlertView
//
//  Created by apple on 2018/2/7.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "UICustomTextAlertView.h"
#import "UITopLineButton.h"

//屏幕的宽高
#define kMianScreenBoundsWidth [UIScreen mainScreen].bounds.size.width
#define kMianScreenBoundsHeight [UIScreen mainScreen].bounds.size.height

//containerView的左右间距
#define kcontainerViewLeftRightMargin 20

//containerView内部控件布局
//标题顶部间距
#define kTitleLabelTopMargin 15

//文字左右间距
#define kMessageLeftRightMargin 20

//文字左右间距
#define kMessageTopBottomMargin 20

//最大间距
#define kMessageLeftRightMaxWidth  ((kMianScreenBoundsWidth - 2*kcontainerViewLeftRightMargin)-2*kMessageLeftRightMargin)



@interface UICustomTextAlertView()

@property (nonatomic, strong) UIView *containerView;

//标题
@property (nonatomic, strong) UILabel *titleLabel;
//内容
@property (nonatomic, strong) UILabel *messageLabel;

//顶部线
@property (nonatomic, strong) UIImageView *centerSepeletorLine;

//最后一个view
@property (nonatomic, strong) UIView *lastView;

@property (nonatomic, strong) NSMutableArray <UITopLineButton *>*buttons;

//数据
@property (nonatomic, strong) NSArray <NSString *>*buttonTitles;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *message;



@end

@implementation UICustomTextAlertView

#pragma mark - 实例方法
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate buttonTitles:(NSString *)buttonTitle, ...
{
    if(self = [super init])
    {
        va_list args;
        va_start(args,buttonTitle);
        NSMutableArray *tempButtons = [NSMutableArray array];
        for (NSString *btnTitle = buttonTitle; btnTitle != nil; btnTitle = va_arg(args, NSString *)) {
            [tempButtons addObject:btnTitle];
        }
        va_end(args);
        self.buttonTitles = tempButtons;
        self.title = title;
        self.message = message;
        self.delegate = delegate;
        
        if(self.title.length == 0)
            self.title = @"温馨提示";
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        
        
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancleAlertView)]];
        //初始化
        [self setupUI];
       
    }
    return self;
}


- (void)setupUI
{
    [self addSubview:self.containerView];
    //标题
    [self.containerView addSubview:self.titleLabel];
    self.titleLabel.text = self.title;
    
    //增加描述
    if(self.message.length > 0){
        [self.containerView addSubview:self.messageLabel];
        self.messageLabel.text = self.message;
    }
    
    //中间分割线
    if(self.buttonTitles.count == 2){
        [self.containerView addSubview:self.centerSepeletorLine];
    }
    
    //加载选择按钮
    [self.buttons removeAllObjects];
    for (NSInteger i = 0; i < self.buttonTitles.count; i++) {
        UITopLineButton *customButton = [[UITopLineButton alloc]initWithButtonHeight:0 lineHeight:0];
        [self.containerView addSubview:customButton];
        customButton.button.tag = i;
        NSString *title = self.buttonTitles[i];
        [customButton.button setTitle:title forState:UIControlStateNormal];
        [customButton.button addTarget:self action:@selector(customButtonTargetAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttons addObject:customButton];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //整个弹框
    self.containerView.center = CGPointMake(kMianScreenBoundsWidth*0.5, kMianScreenBoundsHeight *0.5);
    CGFloat containViewWidth = kMianScreenBoundsWidth - 2*kcontainerViewLeftRightMargin;
    CGFloat maxContainViewWidth = containViewWidth - 2*kMessageLeftRightMargin;
    
    
    //标题
    CGFloat titleLabelX = kMessageLeftRightMargin;
    CGFloat titleLabelY = kTitleLabelTopMargin;
    CGFloat titleLabelW = maxContainViewWidth;
    CGFloat titleLabelH = [self getTitleLabelHeight];
    self.titleLabel.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
     self.lastView = self.titleLabel;
    
    //描述
    if(self.message.length > 0){
        CGFloat messageLabelX = kMessageLeftRightMargin;
        CGFloat messageLabelY = CGRectGetMaxY(self.lastView.frame)+kMessageTopBottomMargin;
        CGFloat messageLabelW = maxContainViewWidth;
        CGFloat messageLabelH = [self getMessageLabelHeight];
        self.messageLabel.frame = CGRectMake(messageLabelX, messageLabelY, messageLabelW, messageLabelH);
        self.lastView = self.messageLabel;
    }
    
    //选择按钮
    if(self.buttons.count ==2){
       //左边按钮
       CGFloat centerLineWidth = 1;
       UITopLineButton *leftButton = self.buttons.firstObject;
        CGFloat buttonY = CGRectGetMaxY(self.lastView.frame) + kMessageTopBottomMargin;
        CGFloat leftButtonWidth = containViewWidth *0.5-centerLineWidth*0.5;
        CGFloat rightButtonWidth = leftButtonWidth;
        CGFloat buttonHeight = [leftButton getTopLineButtonHieght];
        leftButton.frame = CGRectMake(0,buttonY , leftButtonWidth, buttonHeight);
        
        //中心线
        self.centerSepeletorLine.frame = CGRectMake(CGRectGetMaxX(leftButton.frame), buttonY, centerLineWidth, buttonHeight);
        
        //右边按钮
        UITopLineButton *rightButton = self.buttons.lastObject;
        rightButton.frame = CGRectMake(CGRectGetMaxX(self.centerSepeletorLine.frame),buttonY , rightButtonWidth, buttonHeight);
        self.lastView = leftButton;
        
    }else{
        
        for (NSInteger i = 0; i < self.buttons.count; i++)
        {
            UITopLineButton *seletButton = self.buttons[i];
            CGFloat seletButtonX = 0;
            CGFloat seletButtonY = (i == 0)?CGRectGetMaxY(self.lastView.frame) + kMessageTopBottomMargin:CGRectGetMaxY(self.lastView.frame);
            CGFloat seletButtonW = containViewWidth;
            CGFloat seletButtonH = [seletButton getTopLineButtonHieght];
            seletButton.frame = CGRectMake(seletButtonX, seletButtonY, seletButtonW, seletButtonH);
            self.lastView = seletButton;
        }
        
    }
}

#pragma mark - 事件
-(void)show
{
    [self showInView:nil];
}

-(void)showInView:(UIView *)superView
{
    if(superView == nil){
        superView = [UIApplication sharedApplication].keyWindow;
    }
    
    self.frame = [UIScreen mainScreen].bounds;
    [superView addSubview:self];
    
    self.alpha = 0.0;
    [UIView animateWithDuration:0.5 animations:^{
       self.alpha = 1.0;
    }];
    
    //布局
    CGFloat containViewWidth = kMianScreenBoundsWidth - 2*kcontainerViewLeftRightMargin;
    CGFloat containViewHeight = [self getContainViewHeight];
    self.containerView.bounds = CGRectMake(0, 0, containViewWidth, containViewHeight);
    [self shakeToShow:self.containerView];
    
}

- (void)cancleAlertView
{
    self.alpha = 1.0;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self.containerView removeFromSuperview];
        [self removeFromSuperview];
    }];
}

- (void)customButtonTargetAction:(UIButton *)button
{
    NSInteger index = button.tag;
    if([self.delegate respondsToSelector:@selector(customAlertView:didSelectIndex:)]){
        [self.delegate customAlertView:self didSelectIndex:index];
    }
    if(self.clickBlock)
        self.clickBlock(index);
    [self cancleAlertView];
}

//弹出放大-缩小效果
- (void) shakeToShow:(UIView*)aView
{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

#pragma mark - lazy
- (CGFloat)getContainViewHeight
{
     CGFloat height = 0;
    if(self.title.length > 0){
        height = kTitleLabelTopMargin + [self getTitleLabelHeight];
    }
    
    if(self.message.length > 0){
        height = height + kMessageTopBottomMargin + [self getMessageLabelHeight];
    }
    
    height = height + kMessageTopBottomMargin;
    
    if(self.buttons.count == 2){
        UITopLineButton *button = self.buttons.firstObject;
        height = height + [button getTopLineButtonHieght];
    }else{
        UITopLineButton *button = self.buttons.firstObject;
        height = height + [button getTopLineButtonHieght] * self.buttons.count;
    }
    
    return height;
}

- (CGFloat)getTitleLabelHeight
{
    CGFloat height = ceil([self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : self.titleLabel.font}].height);
    return height;
}

- (CGFloat)getMessageLabelHeight
{
    CGFloat height = ceil([self.messageLabel.text boundingRectWithSize:CGSizeMake(kMessageLeftRightMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.messageLabel.font} context:nil].size.height);
    return height;
}

- (UIView *)containerView
{
    if(!_containerView){
        _containerView = [[UIView alloc]init];
        _containerView.backgroundColor = [UIColor whiteColor];
        _containerView.layer.cornerRadius = 5.0;
        _containerView.layer.masksToBounds = YES;
    }
    return _containerView;
}

- (UILabel *)titleLabel
{
    if(!_titleLabel){
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightBold];
        _titleLabel.text = @"系统提示";
    }
    return _titleLabel;
}

- (UILabel *)messageLabel
{
    if(!_messageLabel){
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.textColor = [UIColor blackColor];
        _messageLabel.font = [UIFont systemFontOfSize:14.0];
        _messageLabel.numberOfLines = 0;
        _messageLabel.text = @"系统提示";
    }
    return _messageLabel;
}

- (UIImageView *)centerSepeletorLine
{
    if(!_centerSepeletorLine){
        _centerSepeletorLine = [[UIImageView alloc]init];
        _centerSepeletorLine.backgroundColor = [UIColor grayColor];
        _centerSepeletorLine.contentMode = UIViewContentModeScaleAspectFill;
        _centerSepeletorLine.clipsToBounds = YES;
    }
    return _centerSepeletorLine;
}

- (NSMutableArray<UITopLineButton *> *)buttons
{
    if(!_buttons)
    {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}

@end
